<?php
Class model {
	
	const TYPE_TEXT 	= 1;
	const TYPE_INT 		= 2;
	const TYPE_FLOAT 	= 3;
	const TYPE_DATETIME = 4;
	const TYPE_DATE 	= 5;
	const TYPE_TIME 	= 6;
	
	private $_name;
	private $_structure;
	
	function __construct() {
		$this->_name = get_class($this);
	}
	
	function getName() {
		return $this->_name;
	}
	
	function getData($filter = "1") {
		$db = db::getInstance();
		$db->select("SELECT * FROM $this->_name WHERE $filter");
		return $db->get_obj();
	}
	
	function sql($sql) {
		$db = db::getInstance();
		$db->select($sql);
		return $db->get_obj();
	}
	
	function query(query $query) {
		$db = db::getInstance();
		$db->select($query->render());
		return $db->get_obj();
	}
	
	function getStructure() {
		$db = db::getInstance();
		$db->select("DESCRIBE $table");
		$this->_structure = $db->get_obj();
		return $this->_structure;	
	}
	
	/**
	 * @param integer $id
	 * @return model
	 */
	function loadById($id) {
		$db = db::getInstance();
		$db->select("SELECT * FROM $this->_name WHERE id = $id");
		$res = $db->get_row();
		if ($res) {
			$this->setVars($res);
			return $this;
		} else {
			return false;
		}
	}
	
	/**
	 * @param integer $id
	 * @return model
	 */
	function loadByField($field, $value) {
		$db = db::getInstance();
		$db->select("SELECT * FROM $this->_name WHERE $field = '".addslashes($value)."'");
		$res = $db->get_row();
		if ($res) {
			$this->setVars($res);
			return $this;
		} else {
			return false;
		}
	}
	
	/**
	 * 
	 * @param mixed $name
	 * @param mixed $value
	 * @return model
	 */
	function set($name, $value) {
		// check for id set?
		$db = db::getInstance(); 
		$res = $db->update_array($this->_name, array($name => $value), "id = $this->id");
		if ($res) {
			return $this;
		} else {
			return false;
		}
	}
		
	function get($name) {
		return $this->$name;
	}
	
	function setArray($array) {
		foreach($array as $key => $value) {
			$res = $res * $this->set($key, $value);
		}
		if ($res) {
			return $this;
		} else {
			return false;
		}
	}
	
	function insert($array) {
		$db = db::getInstance();
		return $db->insert_array($this->_name, $array);
	}
	
	function update($array, $id) {
		$db = db::getInstance();
		return $db->update_array($this->_name, $array, "id = $id");
	}
	
	function delete($id) {
		$db = db::getInstance();
		return $db->update_sql("DELETE FROM $this->_name WHERE id = $id");
	}
	
	function getType($name) {
		foreach($this->_structure as $column) {
			if (strtolower($column->Field) == strtolower($name)) {
				// do something
			}
		}
	}
	
	private function setVars($row) {
		foreach ($row as $key => $value) {
			$this->$key = $value;
		}
	}
	
}

?>